using Bingo.API.Player;
using Bingo.Helper;
using CatLib;
using UnityEngine;

namespace Bingo
{
    public class PlayerSystem : IPlayer
    {
        public const string PLAYER_LEVEL = "PLAYER_LEVEL";

        public const string PLAYER_MAP_LEVEL = "PLAYER_MAP_LEVEL";

        private int _playerLevel;

        private int _playerMapLevel;

        private IPlayer _playerImplementation;

        private Color _themeColor;

        private int _lastLevel;

        public int PlayerLevel
        {
            get => GetPlayerLevel();
            set => SetPlayer(value);
        }

        public int PlayerMapLevel
        {
            get => _playerMapLevel;
        }

        public void Load()
        {
            _playerLevel = Facades.LocalDB.Get<int>(PLAYER_LEVEL, 1);
            _playerMapLevel = RandomLevel(_playerLevel);
            _playerMapLevel = Facades.LocalDB.Get<int>(PLAYER_MAP_LEVEL, _playerMapLevel); //随机地图
            Facades.LocalDB.Save(PLAYER_MAP_LEVEL, _playerMapLevel);
            _lastLevel = _playerMapLevel;
            ChangeTheme();
        }

        public Color ChangeTheme()
        {
            string[] color = Arr.Rand(UIConst.UI_Theme);
            _themeColor = ColorHelper.GetColor(color[0]);
            App.Trigger(EventConst.EVENT_UI_CHANGE_BACKGROUND_COLOR, _themeColor);
            return _themeColor;
        }

        public Color GetCurrentTheme()
        {
            return _themeColor;
        }


        private void SetPlayer(int level)
        {
            _playerLevel = level;
            _playerMapLevel = RandomLevel(level);
            _lastLevel = _playerMapLevel;
            Facades.LocalDB.Save(PLAYER_LEVEL, _playerLevel);
            Facades.LocalDB.Save(PLAYER_MAP_LEVEL, _playerMapLevel);
        }

        private int GetPlayerLevel()
        {
            return _playerLevel;
        }

        private int RandomLevel(int level)
        {
            if (level > 80)
            {
                do
                {
                    System.Random random = Util.MakeRandom();
                    level = random.Next(1, 81);
                } while (level == _lastLevel);
            }

            return level;
        }
    }
}